<?php
namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Overtrue\EasySms\EasySms;
use App\User;
use Illuminate\Validation\Rule;
use App\Service\Facades\Sms;

class SmsController extends BaseController
{
    /**
     * 发送验证码
     *
     * @param Request $request
     * @param EasySms $easySms
     * @return void
     */
    public function send(Request $request)
    {
        $rules = [
            'tel'          => 'bail|required|regex:/^1[34578]\d{9}$/',
            'action'       => ['required', Rule::in(['login', 'reg', 'forget'])],
        ];
        $this->validate($request, $rules, [], User::attribute);

        $action  = $request->get('action');
        $tel     = $request->get('tel');

        switch ($action) {
            case 'reg':
                if(User::findUserByTel($tel))  return $this->failed('手机号已存在');
                break;
            case 'forget':
                if (!User::findUserByTel($tel))  return $this->failed('手机号不存在');
                break;
        }
        $verifyKey = Sms::send($tel);
        return $this->success(['key' => $verifyKey]);
     }
}
